package com.mysteel.product.exception;

import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ProjectName: mail
 * ClassName: ExceptionResultValid
 * Description: 集中处理所有异常
 * date: 2020/12/30/030 9:47
 *
 * @author xiaochao
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.mysteel.product.controller")
public class ExceptionHandle {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.info("数据校验出现异常{}", e.getMessage());
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String,String> errorMap = new HashMap<>();
        fieldErrors.forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.PARAMETER_VALID_EXCEPTION.getCode(),BizCodeEnum.PARAMETER_VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleCommonException(Throwable throwable) {
        log.info("异常信息：{}", throwable);

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
